//引入内置或第三方插件
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var session = require('express-session');
var mysql2 = require('mysql2/promise');
var MySQLStore = require('express-mysql-session')(session);


//引入一级路由 
var apiRouter = require('./routes/api');
var indexRouter = require('./routes/index');
var moduleRouter = require('./routes/module');

var adminRouter = require('./routes/subsys_routes/admin.routes');
var authorityRouter = require('./routes/subsys_routes/authority.routes');
var companyRouter = require('./routes/subsys_routes/company.routes');
var customerRouter = require('./routes/subsys_routes/customer.routes');
var marketRouter = require('./routes/subsys_routes/market.routes');
var qrcodeRouter = require('./routes/subsys_routes/qrcode.routes');
var traceRouter = require('./routes/subsys_routes/trace.routes');
var transportRouter = require('./routes/subsys_routes/transport.routes');

//创建一个服务器
var app = express();

// view 引擎启动，设置静态资源目录
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//跨域设置

app.use(cors());

//注册插件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//登录验证拦截,设置session数据库
var options = {
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '666666',		
  database: 'session'
};

var sessionConnection = mysql2.createPool(options);
var sessionStore = new MySQLStore({
  expiration: 1000*60*60*24*7,
  createDatabaseTable: true,	//是否创建表
  schema: {
      tableName: 'session_tab',	//表名
      columnNames: {		//列选项
          session_id: 'session_id',
          expires: 'expires',
          data: 'data'
      }
  }
}, sessionConnection);

app.use(session({
key: 'trace system',
secret: "session_key_secret",
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: ('name','value',{	
  maxAge:  2*60*60*1000,
  secure: false,
  httpOnly:false
  })
}));

app.use((req,res,next)=>{
  if(req.url.includes("regist")){
    next();
    return;
  }
  if(req.url.includes("login")){
    next();
    return;
  }
  if(req.url.includes("logout")){
    next();
    return;
  }
  if(req.session.state){
    req.session.correction = Date.now();
    next();
  }else{
    res.send({'command':'redirect to login'});
  }
});

//注册顶级路由
app.use('/', indexRouter);
app.use('/api', apiRouter);
app.use('/index', indexRouter);
app.use('/module', moduleRouter);

//注册模块路由
app.use('/admin', adminRouter);
app.use('/company', companyRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

//同步数据库
const db = require('./database/models');
db.sequelize.sync();

module.exports = app;
